import actionTypes from './actionTypes'
import { loginApi } from '../../api'

// 只有同步的内容才定义actionType（跟vue一致）

const startLogin = () => {
  return {
    type: actionTypes.START_LOGIN
  }
}

const loginSuccess = (userInfo) => {
  return {
    type: actionTypes.LOGIN_SUCCESS,
    payload: {
      userInfo
    }
  }
}

const loginFailed = () => {
  // 登录失败，清楚登录相关的信息
  window.localStorage.removeItem('authToken')
  window.sessionStorage.removeItem('authToken')
  window.localStorage.removeItem('userInfo')
  window.sessionStorage.removeItem('userInfo')
  return {
    type: actionTypes.LOGIN_FAILED
  }
}

export const login = (userInfo) => {
  return dispatch => {
    dispatch(startLogin())
    // 这里是模拟的服务端的请求 （是否成功）
    loginApi(userInfo)
      .then(res => {
        // console.log(res)
        const {
          authToken,
          ...userInfo
        } = res.data.data
        if (res.data.code === 200) {
          if (userInfo.remember === true) {
            window.localStorage.setItem('authToken', authToken)
            window.localStorage.setItem('userInfo', JSON.stringify(userInfo))
          } else {
            window.sessionStorage.setItem('authToken', authToken)
            window.sessionStorage.setItem('userInfo', JSON.stringify(userInfo))
          }
          
          dispatch(loginSuccess(res.data.data))
          // dispatch(loginSuccess({
          //   ...res.data.data,
          //   remember: userInfo.remember
          // }))
        } else {
          dispatch(loginFailed())
        }
      })
  }
}

// 用户退出
export const logout = () => {
  return dispatch => {
    // 实际项目中要告诉服务端，用户已经退出
    dispatch(loginFailed())
  }
}

// 更新头像
export const changeAvatar = (avatarUrl) => {
  return {
    type: actionTypes.CHANGE_AVATAR,
    payload: {
      avatarUrl
    }
  }
}